package com.example.schedule;

import com.example.schedule.entity.Schedule;
import com.example.schedule.handle.base.AbstractSchedule;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ScheduledFuture;

/**
 * @author wangbin
 */
@Service
public class ScheduleService {
    @Resource
    private ApplicationContext applicationContext;
    @Resource
    private ThreadPoolTaskScheduler scheduler;
    @Resource
    private ScheduleRepository scheduleRepository;

    void start(Integer scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).orElseThrow(RuntimeException::new);
        String name = schedule.getName();
        AbstractSchedule bean = applicationContext.getBean(name, AbstractSchedule.class);
        if (!bean.isRunning()) {
            ScheduledFuture<?> future = scheduler.schedule(bean, c -> new CronTrigger(schedule.getCron()).nextExecutionTime(c));
            bean.setScheduledFuture(future);
        }
    }

    void stop(Integer scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).orElseThrow(RuntimeException::new);
        String name = schedule.getName();
        AbstractSchedule bean = applicationContext.getBean(name, AbstractSchedule.class);
        if (bean.isRunning()) {
            ScheduledFuture<?> future = bean.getScheduledFuture();
            future.cancel(true);
            bean.setScheduledFuture(null);
        }
    }
}
